import Vue from 'vue'
import http from 'axios'
import router from '../router/index'
import { Toast } from 'vant'
import QS from 'qs'

Vue.prototype.axios = http

const axios = http.create()

function startLoading() {
  // 开始加载
  Toast.loading({
    message: '加载中...',
    overlay: true,
    duration: 0,
    forbidClick: true
  })
}

function endLoading() {
  // 结束加载
  Toast.clear()
}

// 中断请求配置
Vue.prototype.$httpRequestList = []

axios.defaults.headers['content-type'] = 'application/json;charse=UTF-8'
axios.defaults.timeout = 60000 // 超时时间

// 如果是正式环境，自动取正式环境里面得baseUrl
axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
console.log(axios.defaults.baseURL, 'URl')

// 记录请求次数
let loadingRequestCount = 0

// 请求拦截器
axios.interceptors.request.use(
  config => {
    loadingRequestCount++
    if (loadingRequestCount === 1) {
      startLoading()
    }
    config.contentType = 'application/json'
    config.headers['token'] = window.localStorage.getItem('px_token')
    return config
  },
  error => {
    loadingRequestCount--
    if (loadingRequestCount === 0) {
      endLoading()
    }
    return Promise.reject(error)
  }
)

// 响应拦截器即异常处理
axios.interceptors.response.use(
  response => {
    loadingRequestCount--
    if (loadingRequestCount === 0) {
      endLoading()
    }
    console.log(response, 'respon')
    if (response.data.code === 200) {
      return Promise.resolve(response)
    } else if (response.data.code === 1010) {
      // 请求计数，当还有请求未完成时，不执行跳转
      if (loadingRequestCount !== 0) return
      localStorage.removeItem()
      Toast(response.data.message)
      setTimeout(() => {
        router.push({ name: 'login', params: {} })
      }, 1500)
    } else {
      return Promise.reject(response)
    }
  },
  err => {
    loadingRequestCount--
    if (loadingRequestCount === 0) {
      endLoading()
    }
    if (err && err.response) {
      switch (err.response.code) {
        case 400:
          err.message = '错误请求'
          break
        case 401:
          err.message = '未授权，请重新登录'
          break
        case 403:
          err.message = '没有访问权限，拒绝访问'
          break
        case 404:
          err.message = '请求错误,未找到该资源'
          break
        case 405:
          err.message = '请求方法未允许'
          break
        case 408:
          err.message = '请求超时'
          break
        case 500:
          err.message = err.response.message
          break
        case 501:
          err.message = '网络未实现'
          break
        case 502:
          err.message = '网络错误'
          break
        case 503:
          err.message = '服务不可用'
          break
        case 504:
          err.message = '网络超时'
          break
        default:
          err.message = `连接错误${err.response.msg}`
      }
    } else {
      err.message = '连接到服务器失败'
    }
    return Promise.reject(err.response)
  }
)

export default {
  // get请求
  get(url, param, header) {
    return axios({
      method: 'get',
      url,
      headers: {
        ...(header || {})
      },
      params: param || {}
    })
  },
  // post请求
  post(url, param, header) {
    return axios({
      method: 'post',
      url,
      headers: {
        ...(header || {}),
        'content-type': 'application/json;charset=UTF-8'
      },
      data: param || {}
    })
  },
  postFormData(url, params) {
    return axios({
      method: 'post',
      url,
      headers: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: QS.stringify(params) || {}
    })
  },
  postFile(url, params) {
    return axios({
      method: 'post',
      url,
      headers: {
        'content-type': 'multipart/form-data'
      },
      data: QS.stringify(params) || {}
    })
  },
  // post请求
  put(url, param, header) {
    return axios({
      method: 'put',
      url,
      headers: {
        ...(header || {}),
        'content-type': 'application/json;charse=UTF-8'
      },
      data: param || {}
    })
  },
  // delete
  delete(url, param, header) {
    return axios({
      method: 'delete',
      url,
      headers: {
        ...(header || {})
      },
      params: param || {}
    })
  }
}
